import { NextRequest } from 'next/server';
import prisma from '@/lib/prisma';
import { ResponseUtil } from '@/utils/response';
import { verifyAuth } from '@/utils/auth';

// 点赞/取消点赞
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { user } = await verifyAuth(request);
    if (!user) {
      return ResponseUtil.unauthorized('请先登录');
    }

    const postId = parseInt((await params).id);
    
    // 检查帖子是否存在
    const post = await prisma.forumPost.findUnique({
      where: { id: postId },
    });

    if (!post) {
      return ResponseUtil.notFound('帖子不存在');
    }

    // 检查是否已经点赞
    const existingLike = await prisma.forumPostLike.findFirst({
      where: {
        postId: postId,
        userId: user.id,
      },
    });

    if (existingLike) {
      // 如果已经点赞，则取消点赞
      await prisma.forumPostLike.delete({
        where: { id: existingLike.id },
      });

      // 减少帖子点赞数
      await prisma.forumPost.update({
        where: { id: postId },
        data: {
          likeCount: {
            decrement: 1,
          },
        },
      });

      return ResponseUtil.success({
        isLiked: false,
        likeCount: post.likeCount - 1,
        message: '取消点赞成功',
      });
    } else {
      // 如果未点赞，则添加点赞
      await prisma.forumPostLike.create({
        data: {
          postId: postId,
          userId: user.id,
        },
      });

      // 增加帖子点赞数
      await prisma.forumPost.update({
        where: { id: postId },
        data: {
          likeCount: {
            increment: 1,
          },
        },
      });

      return ResponseUtil.success({
        isLiked: true,
        likeCount: post.likeCount + 1,
        message: '点赞成功',
      });
    }
  } catch (error) {
    console.error('点赞操作失败:', error);
    return ResponseUtil.error('点赞操作失败');
  }
}

// 获取点赞状态
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { user } = await verifyAuth(request);
    if (!user) {
      return ResponseUtil.unauthorized('请先登录');
    }

    const postId = parseInt((await params).id);
    
    // 检查是否已经点赞
    const existingLike = await prisma.forumPostLike.findFirst({
      where: {
        postId: postId,
        userId: user.id,
      },
    });

    return ResponseUtil.success({
      isLiked: !!existingLike,
    });
  } catch (error) {
    console.error('获取点赞状态失败:', error);
    return ResponseUtil.error('获取点赞状态失败');
  }
} 